package com.fengpb.friday.conductor.client.warpper;

import com.fengpb.friday.conductor.common.dto.HttpStatusEnum;
import com.fengpb.friday.conductor.common.dto.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice(annotations = RestController.class)
public class RestResultWrapper implements ResponseBodyAdvice<Object> {

    private static final Logger log = LoggerFactory.getLogger(RestResultWrapper.class);

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if ("start".equals(methodParameter.getMethod().getName())) {
            return o;
        }
        if (o instanceof Response) {
            Response response = (Response) o;
            if (!StringUtils.hasText(response.getPath())) {
                response.setPath(serverHttpRequest.getURI().getPath());
            }
            return response;
        } else {
            return new Response(HttpStatusEnum.SUCCESS, o, serverHttpRequest.getURI().getPath());
        }
    }

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Response errorHandler(HttpServletRequest request, Exception e) {
        log.error("request error", e);
        return new Response(HttpStatusEnum.FAILED.status(), e.getMessage(), request.getRequestURI());
    }
}
